<script setup lang="ts">
import { ref, reactive, computed } from "vue";
import { useColumns } from "./columns";
import { tableDataTemp } from "./data";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import "plus-pro-components/es/components/search/style/css";

import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { PureTableBar } from "@/components/RePureTableBar";

import Upload from "@iconify-icons/ri/upload-line";
import Role from "@iconify-icons/ri/admin-line";
import Password from "@iconify-icons/ri/lock-password-line";
import More from "@iconify-icons/ep/more-filled";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import AddFill from "@iconify-icons/ri/add-circle-line";

const query = ref({
  certificateNumber: "",
  certificateType: "",
  validityPeriod: "",
  qualificationCategoryAndLevel: "",
  companyName: "",
  legalRepresentative: ""
});

const form = ref({
  certificateNumber: "",
  certificateType: "",
  validityPeriod: "",
  qualificationCategoryAndLevel: "",
  companyName: "",
  legalRepresentative: "",
  registeredCapital: "",
  economicNature: "",
  detailAddress: "",
  remark: "",
  imageUrl: ""
});

const visible = ref(false);
const modalTitle = ref("新增");
const currentRow = ref(null);
const fileList = ref([]);
const formDisabled = computed(() => modalTitle.value === "查看");

const certificateTypeOpts = reactive([
  { label: "资质证书", value: "1" },
  { label: "安全生产许可证", value: "2" },
  { label: "建筑业证书", value: "3" },
  { label: "其他", value: "4" }
]);
const searchColumns: PlusColumn[] = [
  {
    label: "证书编号",
    prop: "certificateNumber"
  },
  {
    label: "证书类型",
    prop: "certificateType",
    valueType: "select",
    options: certificateTypeOpts
  },
  {
    label: "有效期",
    prop: "validityPeriod",
    valueType: "date-picker"
  },
  {
    label: "资质类别及等级",
    prop: "qualificationCategoryAndLevel"
  },
  {
    label: "企业名称",
    prop: "companyName"
  },
  {
    label: "法定代表",
    prop: "legalRepresentative"
  },
  {
    label: "注册资本",
    prop: "registeredCapital",
    align: "right"
  },
  {
    label: "经济性质",
    prop: "economicNature"
  }
];

const handleChange = (values: any) => {
  console.log(values, "change");
};
const handleSearch = (values: any) => {
  console.log(values, "search");
};
const handleRest = () => {
  console.log("handleRest");
};
const openDialog = (title: any, row?: any) => {
  if (row) {
    currentRow.value = row;
    form.value = { ...row };
  }
  modalTitle.value = title;
  visible.value = true;
};
const closeDialog = () => {
  currentRow.value = null;
  form.value = {
    certificateNumber: "",
    certificateType: "",
    validityPeriod: "",
    qualificationCategoryAndLevel: "",
    companyName: "",
    legalRepresentative: "",
    registeredCapital: "",
    economicNature: "",
    detailAddress: "",
    remark: "",
    imageUrl: ""
  };
  fileList.value = [];
  visible.value = false;
};
const resetDialogForm = () => {
  if (modalTitle.value === "新增") {
    form.value = {
      certificateNumber: "",
      certificateType: "",
      validityPeriod: "",
      qualificationCategoryAndLevel: "",
      companyName: "",
      legalRepresentative: "",
      registeredCapital: "",
      economicNature: "",
      detailAddress: "",
      remark: "",
      imageUrl: ""
    };
  } else {
    form.value = { ...currentRow.value };
  }
};
const changeFormTitle = () => {
  modalTitle.value = "修改";
};
const handleUploadSuccess = (res: any, file: any) => {
  console.log(res, file, "handleUploadSuccess");
};
const handleUploadError = (err: any, file: any) => {
  console.log(err, file, "handleUploadError");
};
const handleUploadRemove = (file: any) => {
  console.log(file, "handleUploadRemove");
};
const handleDelete = row => {
  console.log(
    "%crow===>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
};

const tableRef = ref();

const {
  loading,
  columns,
  pagination,
  loadingConfig,
  onSizeChange,
  onCurrentChange
} = useColumns();
</script>

<template>
  <div>
    <PlusSearch
      v-model="query"
      :columns="searchColumns"
      :show-number="2"
      label-width="120"
      label-position="right"
      @change="handleChange"
      @search="handleSearch"
      @reset="handleRest"
    />
    <PureTableBar title="证书列表" :columns="columns" @refresh="handleSearch">
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog('新增')"
        >
          新增证书
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          row-key="id"
          alignWhole="center"
          table-layout="auto"
          border
          sortable
          showOverflowTooltip
          adaptive
          :adaptiveConfig="{ offsetBottom: 108 }"
          :size="size"
          :loading="loading"
          :loading-config="loadingConfig"
          :columns="dynamicColumns"
          :pagination="{ ...pagination, size }"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="
            tableDataTemp.slice(
              (pagination.currentPage - 1) * pagination.pageSize,
              pagination.currentPage * pagination.pageSize
            )
          "
          @page-size-change="onSizeChange"
          @page-current-change="onCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon('ri:search-line')"
              @click="openDialog('查看', row)"
            >
              查看
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('修改', row)"
            >
              修改
            </el-button>
            <el-popconfirm
              width="200px"
              :title="`是否确认删除证书编号：${row.certificateNumber}？`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon(Delete)"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-drawer
      v-model="visible"
      :title="modalTitle"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      direction="rtl"
      size="50%"
    >
      <el-form :model="form" label-width="auto" :disabled="formDisabled">
        <el-form-item prop="certificateNumber" label="证书编号" required>
          <el-input
            v-model="form.certificateNumber"
            autocomplete="off"
            :disabled="formDisabled"
          />
        </el-form-item>
        <el-form-item prop="certificateType" label="证书类型" required>
          <el-select
            v-model="form.certificateType"
            placeholder="请选择证书类型"
          >
            <el-option
              v-for="item in certificateTypeOpts"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="validityPeriod" label="有效期" required>
          <el-date-picker
            v-model="form.validityPeriod"
            type="date"
            placeholder="请选择有效期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item
          prop="qualificationCategoryAndLevel"
          label="资质类别及等级"
          required
        >
          <el-input
            v-model="form.qualificationCategoryAndLevel"
            placeholder="请输入资质类别及等级"
          />
        </el-form-item>
        <el-form-item prop="companyName" label="企业名称" required>
          <el-input
            v-model="form.companyName"
            autocomplete="off"
            placeholder="请输入企业名称"
          />
        </el-form-item>
        <el-form-item prop="legalRepresentative" label="法定代表" required>
          <el-input
            v-model="form.legalRepresentative"
            autocomplete="off"
            placeholder="请输入法定代表"
          />
        </el-form-item>
        <el-form-item prop="registeredCapital" label="注册资本">
          <el-input
            v-model="form.registeredCapital"
            autocomplete="off"
            placeholder="请输入注册资本"
          />
        </el-form-item>
        <el-form-item prop="economicNature" label="经济性质" required>
          <el-input
            v-model="form.economicNature"
            autocomplete="off"
            placeholder="请输入经济性质"
          />
        </el-form-item>
        <el-form-item prop="detailAddress" label="详细地址">
          <el-input
            v-model="form.detailAddress"
            autocomplete="off"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item prop="remark" label="备注">
          <el-input
            v-model="form.remark"
            autocomplete="off"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            class="upload-demo"
            action="#"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleUploadRemove"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button size="small" type="primary"> 点击上传 </el-button>
            <template v-slot:tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item v-show="form.imageUrl" label="预览">
          <el-image
            style="width: 100px; height: 100px"
            :src="form.imageUrl"
            fit="cover"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="[form.imageUrl]"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            v-show="!formDisabled"
            type="warning"
            @click="resetDialogForm"
            >重 置</el-button
          >
          <el-button
            v-show="formDisabled"
            type="warning"
            @click="changeFormTitle"
            >修 改</el-button
          >
          <el-button type="primary">确 定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped></style>
